www.gusucode.com > XerCMS 携云PHP企业建站程序 v2015PHP源码程序 > XerCMS 携云PHP企业建站程序 v2015/XerCMS_v20150724/XerCMS_v20150724/XerCMS/Utils/XerCMS_base.php

    <?php
/**
 * @name     XERCMS
 * @author   Arno <XerCMS@163.com> [QQ:1328013]
 * @version  1.0.0
 * @link     http://www.XerCMS.com 
 */

!defined('XERCMS') && exit('Access Denied');

function html($str) {
     return $str;
}

function Xround($number,$divisor,$prec = 2,$suffix = '') {
     return $divisor > $number ? $number : round($number/$divisor,$prec).$suffix;
}

function Act($name) {
     if(isset(X::$XERCMS['ACTIONS'][$name])) {
          return X::$XERCMS['ACTIONS'][$name];
     }
     $CLASS = 'ACTION_'.$name;
     X::import($name.'.php',DIR.'actions/');
     X::$XERCMS['ACTIONS'][$name] = new $CLASS();
     return X::$XERCMS['ACTIONS'][$name];
}

function executor() {
     
}

function setPath($layer) {
     X::$G['urlpath'] = $_SERVER['SCRIPT_NAME'];
     for($i=0;$i<$layer;$i++) {
          X::$G['urlpath'] = dirname(X::$G['urlpath']);
     }
     X::$G['urlpath'] = strtr(X::$G['urlpath'],array('\\'=>'/'));
     if(X::$G['urlpath'] != '/') {
          X::$G['urlpath'] .= '/';
     }     
}

function domains() {
     $file = INC.'Data/domains/'.htmlentities(trim($_SERVER['SERVER_NAME'])).'.config';
     if(!file_exists($file)) {
          include_once(tpl('common/domains.htm'));exit;
     }
	$domains = file($file);
	if($domains !== false) {
		foreach($domains as $v) {
			if(strpos($v,'=') !== false) {
		    		$v = explode('=',$v,2);
				if(!isset($_GET[$v[0]])) {
              			$_GET[$v[0]] = trim($v[1]);
				}
		  	}
        	}		
	}
	unset($domains);
}

function valid($CLASS = null) {
     if(empty($CLASS)) {
	     if(isset(X::$XERCMS['Valid'])) {
	          return X::$XERCMS['Valid'];
          } else {
               X::$XERCMS['Valid'] = new Valid();
               return X::$XERCMS['Valid'];
          } 
     } else {
          $CLASS = 'Valid_'.$CLASS;
          if(isset(X::$XERCMS[$CLASS])) {
               return X::$XERCMS[$CLASS];
          }
          X::import($CLASS.'.php',XERCMS.'XerCMS/Utils/validate/');         
          X::$XERCMS[$CLASS] = new $CLASS();
          return X::$XERCMS[$CLASS];
     }
}

function utils($name) {
     X::import($name,'utils');
}

function rs($table) {
     global $XERCMS;$CLASS = 'TABLE_'.$table;
	if(isset($XERCMS[$CLASS]))
	     return $XERCMS[$CLASS];
	if(is_file(XERCMS.'XerCMS/Utils/tables/XerCMS_'.$table.'.php')) {
	 	X::import('XerCMS_'.$table.'.php',XERCMS.'XerCMS/Utils/tables/');
          $XERCMS[$CLASS] = new $CLASS(); 	 
	} else {
	 	X::import('resource');
          $XERCMS[$CLASS] = new resource();  	
		$XERCMS[$CLASS]->table = $table;
	}
	return $XERCMS[$CLASS];
}

function session($args) {
	return is_array($args) ? session::set($args) : session::val($args);
}

function jsonSql($data) {
     return strtr(json_encode($data),array('\\'=>'\\\\','\''=>'\\\''));
}

function M($name) {
     $class = 'XerCMS_Interface_'.$name;
     if(isset(X::$XERCMS[$class])) {
          return X::$XERCMS[$class];
     } else {
          X::import(INC.'Modules/'.$name.'/libs/XerCMS_Interface_'.$name.'.php',null);
          X::$XERCMS[$class] = new $class();
          return X::$XERCMS[$class];
     }
}

function obstart() {
	global $error;
	$error[] = '';
	ob_end_clean();
	ob_start();
}

function random($number = 32) {
	$str = '';
	$randstr = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',0,1,2,3,4,5,6,7,8,9);
	for($i = 0;$i < $number;$i++) {
		$str .= $randstr[mt_rand(0,35)];
	}
	return $str;
}

function st($str,$var) {
	$arr = array();
	foreach($var as $k=>$v) {
		$arr['{xercms$'.$k.'}'] = $v;
	}
	return strtr($str,$arr);
}

function sendemail($username,$addr,$title,$body) {
	global $G,$XERCMS;
	libs('mail.class');
	$mail = new MAIL($XERCMS['CONFIG']['smtp_host'],$XERCMS['CONFIG']['smtp_user'],$XERCMS['CONFIG']['smtp_pass'],$XERCMS['CONFIG']['smtp_port'], "\r\n",5);
	//$mail->enableDebug(true);
	$mail->setFrom(X::$G['sitename'],$XERCMS['CONFIG']['smtp_mail']);
	$mail->setTo(array($username=>$addr));
	$mail->send($title,$body);
	//echo $mail->error;
}

function smIds($mId) {
	global $XERCMS;
	if(isset($XERCMS['special'][$mId]) == false) {
    		$XERCMS['special'][$mId] = ini('special/'.$mId);
  	}
  	return $XERCMS['special'][$mId];
}

function letter($str,$utf8 = true) {
     if(preg_match('/[A-Za-z]/',$str,$match)) {
          return strtoupper($match[0]);
     } else  {
          if($utf8 == true) {
               $str = mb_convert_encoding($str,'gbk','utf-8');
          }
          if(preg_match('/[\x80-\xff]{2}/',$str,$match)) {
		     $int = ord($match[0]{0})*256  + ord($match[0]{1});
    	     	$range = array('Z'=>54481,'Y'=>53689,'X'=>52980,'W'=>52698,'T'=>52218,'S'=>51446,'R'=>51387,'Q'=>50906,'P'=>50622,'O'=>50614,'N'=>50371,'M'=>49896,'L'=>49324,'K'=>49062,'J'=>48119,'H'=>47614,'G'=>47297,'F'=>47010,'E'=>46826,'D'=>46318,'C'=>45761,'B'=>45253,'A'=>45217);
   	     	foreach($range as $k=>$v) {
	    	     	if($int > $v) {
		 	     	return $k;
		 		}
			}
		}
          return 'U';
     }
}

function feed($content,$uid = 0) {
     if(!$uid) { 
		$uid = X::$G['uid'];		 
	}
	DB::update('xercms_member_doing',array('time'=>X::$G['time'],'content'=>$content),'uid = \''.$uid.'\'');
}

function dreferer($url = '/') {
	$referer = isset($_GET['referer']) ? $_GET['referer'] : (isset($_POST['referer']) ? $_POST['referer'] : $_SERVER['HTTP_REFERER']);
	$domain = explode('/',$referer,4);	
	if(isset($domain[2])) {
		if(X::$G['domain'] == $domain[2]) {
			return $referer;
    		}
    
		foreach(X::$G['safedomain'] as $v) {
	  		$pos = strrpos($domain[2],$v);
	  		if($pos !== false && ($pos + strlen($v)) == strlen($domain[2])) {
	    			return $referer;
	  		}
		}
  	}
  	return $url;
}


function ismember() {
	if(X::$G['uid'] < 1) {
    		showtips('must_login',X::$G['urlpath'].'index.php?m=member&a=login');
  	}
}

function dfile($path) {
	if(func_num_args() == 1) {
    		return @file_get_contents(XERCMS.$path);
  	} else {
		$data = func_get_arg(1);
		//$handle = fopen(XERCMS.$path,'w+');
		//fwrite($handle,$data);
		return file_put_contents(XERCMS.$path,$data,LOCK_EX);
	}
}

function cookie($name) {
     $op = func_num_args();
     switch($op) {
          case 1:
		     return isset($_COOKIE[$name]) ? $_COOKIE[$name] : '';
		break;
          case 2:
		     setcookie($name,func_get_arg(1),X::$G['time'] + 86400);
		break;
          case 3:
		     setcookie($name,func_get_arg(1),func_get_arg(2));
		break;
          case 4:
		     setcookie($name,func_get_arg(1),func_get_arg(2),func_get_arg(3));
		break;
     }
}

function isexists($name) {
	if(file_exists(XERCMS.$name)) {
		return true;
	} else {
		try {
			return fopen(XERCMS.$name,'r');
		} catch (Exception $e) {
			return false;
		}
	}
}

function htmlfilter($var) {
	return preg_replace('/<(.*?)>/s','',$var);
}

function sendmessage($uid,$title,$content,$rely = '',$sender = '') {
     $uid = (int)$uid;
  	isset(X::$CONFIG['message']) == false && (X::$CONFIG['message'] = ini('message'));
  	foreach(X::$CONFIG['message']['limit'] as $v) {
		if(!empty($v) && (strpos($title,$v) !== false || strpos($content,$v) !== false)) {
			if(empty($sender)) {
				showtips('message_limit','index.php?m=member&e=message');
	  		} else return false;
		}
  	}
  	$title = strtr($title,X::$CONFIG['message']['replace']);
  	$content = strtr($content,X::$CONFIG['message']['replace']);
  	$sender = empty($sender) ? X::$G['uid'] : $sender;
  	DB::insert('xercms_member_message',array('uid'=>$uid,'title'=>$title,'content'=>$content,'send'=>$sender,'time'=>X::$G['time']));
 	DB::query('UPDATE xercms_member_count SET unread = unread + 1 WHERE uid = '.$uid);
}

function pages($total,$curr,$range,$url) {
     $pages = array();
     for($i = ($curr-$range);$i < $curr;$i++) {
	     if($i > 0)
		     $pages[] = array('page'=>$i,'pageUrl'=>strtr($url,array('[page]'=>$i)));
	}
	$max = $curr + $range;
	$max = $max > $total ? $total : $max;
     for($i = $curr;$i <= $max;$i++) {
	     $pages[] = array('page'=>$i,'pageUrl'=>strtr($url,array('[page]'=>$i)));
	}
	return $pages;
}

function ini($file,$name = '',$value = false) {
	$file = explode('#',$file);
	if(count($file) == 2) {
    		$file = DIR.'Data/'.$file[1].'.php';
  	} else {
		$file = INC.'Data/'.$file[0].'.php';
  	}
  	$isfile = file_exists($file);
  	//exit($file);
 	$config = $isfile ? include($file) : array();
  	if(is_array($name)) {
    		$value = true;
  	}
  	switch($value) {
    		case false:
	  		if(!empty($name)) {
	    			return $config[$name];
	  		} else return $config;
		break;
		default:
			if(is_array($name)) {
	    			$config = is_array($config) ? ($name + $config) : $name;
	  		} else $config[$name] = $value;
	  		$str = $isfile ? file_get_contents($file) : '';
	  		$handle = fopen($file,'w+');
	  		if(flock($handle,LOCK_EX) === true) {
				$str = explode('return',$str,2);
	    			fwrite($handle,(empty($str[0]) ? '<?php !defined(\'XERCMS\') && exit(\'Access Denied\'); ' : $str[0]).'return '.AtoS($config,true).'; ?>');
				flock($handle,LOCK_UN);
	  		}
	  		unset($str);
	  		fclose($handle);
	  		return true;
		break;
  	}
}

function int1($var) {
	$var = (int)$var;
	return $var < 1 ? 1 : $var;
}

function inArray($val,$arr) {
     if(in_array($val,$arr)) {
          return $val;
     } else return current($arr);  
}

function AtoS($in ,$dp = false) {
	if(is_array($in) === false) {
		return 'Array()';
  	}
  	$str = 'Array(';
  	$temp = array();$i = 0;
  	foreach($in as $k=>$v) {
		if(is_array($v)) {
			//print_r($v);
	  		$temp[] = '\''.$k.'\'=>'.AtoS($v);
		} else {
          	if(is_string($v)) {
               	$temp[] = '\''.$k.'\'=>\''.strtr($v,array('\\'=>'\\\\','\''=>'\\\'')).'\'';
          	} else if (is_bool($v)) {
               	$temp[] = '\''.$k.'\'=>'.($v ? 'true' : 'false');
          	} else if (is_int($v)) {
               	$temp[] = '\''.$k.'\'=>'.$v;
          	} else if (is_float($v)) {
               	$temp[] = '\''.$k.'\'=>'.$v;
          	} else if (is_null($v)) {
               	$temp[] = '\''.$k.'\'=>null';
          	} else {
               	$temp[] = '\''.$k.'\'=>\''.strtr((string)$v,array('\\'=>'\\\\','\''=>'\\\'')).'\'';
          	}    
     	}
		$i++;
  	}
  	$str .= implode(',',$temp);
  	return $str.')';
}

function delfile($path) {
     if(file_exists($path)) 
          return unlink($path);
     return true;
}

function f($name) {
  	$name = explode('#',$name);
  	if(count($name) == 2) {
    		include_once(DIR.'libs/'.$name[1].'.php');
  	} else include_once(XERCMS.'xercms/library/'.$name[0].'.php');
}

function htmlchars($str,$replace = array('\''=>'&#39;','"'=>'&#34;','<'=>'&#60;','>'=>'&#62;','*'=>'&#8727;')) {
	return strtr($str,$replace);
}

function arrayfind($arr,$str = '') {
  	return empty($arr) ? false : in_array($str,$arr);
}

function setformat($val) {
  	X::$G['format'] = $val;
}

function multi($total,$page,$number = 30,$url = '',$display = 5) {
	$totalPages = ceil($total/$number);
  	global $links;$linkstr = '';$display++;
  	if(empty($url)) {
    		$linkstr = htmlchars($_SERVER['REQUEST_URI']);
		$linkstr = isset($_GET['page']) ? preg_replace('/page=([0-9]+)/i','page={page}',$linkstr) : $linkstr.'&page={page}';
  	} else {
    		if(isset($links[$url])) {
	  		X::$Get_page = $_GET['page'];unset($_GET['page']);
      		$linkstr = preg_replace('/{([a-z0-9]+)}/i','return $_GET[\'\\1\']',$links[$url]);
	  		$_GET['page'] = X::$Get_page;
    		} else $linkstr = $url.'&page={page}';
  	}
 	$ret = '';
  	for($i = $page - $display;$i<$page;$i++) {
    		if($i <= 0) {
	  		continue;
		} else $ret .= '<li><a href="'.strtr($linkstr,array('{page}'=>$i)).'">'.$i.'</a></li>';
  	}
  	for($i = $page;$i<$page + $display;$i++) {
    		if($i > $totalPages) {
	  		break;
		} else $ret .= '<li><a href="'.strtr($linkstr,array('{page}'=>$i)).'">'.$i.'</a></li>';
  	}
  	if(!empty($ret)) {
    		$ret .= '<li><input type="text" url="'.$linkstr.'" maxpage="'.$totalPages.'" id="xercms_gopage"><a onclick="gopage(\'xercms_gopage\')">GO</a></li>';
  	}
  	//exit($linkstr);
 	return empty($ret) ? '' : '<ul><li class="xercms_count">'.$page.'/'.$totalPages.'</li>'.$ret.'</ul>';
}

function ecredit($member,$need) {
     foreach($need as $k=>$v) {
          if(isset($member['credit'.$k])) {
               if($member['credit'.$k] >= $need) {
                    return true;
               }
          }
     }
	return false;
}

function credits() {
	if(!isset(X::$XERCMS['INSTANCE']['credits'])) {
		X::$XERCMS['INSTANCE']['credits'] = new credits();
  	}
	return X::$XERCMS['INSTANCE']['credits'];
}


function arcpic($file,$id = '1') {
	global $G,$caches;
	if(strpos($file,'http://') !== false) {
		return $file;
	}
	if(isset($caches['_upload'][$id]) == false) {
    		$caches['_upload'] = ini('common/upload');
  	}
  	//print_r($caches);exit;
  	return (empty($caches['_upload'][$id]['host']) ? '' : $caches['_upload'][$id]['host']).X::$G['urlpath'].$caches['_upload'][$id]['path'].$file;
}

function libs($name) {
	 //$name = strtolower($name);
     if(isset(X::$XERCMS['INCLUDE'][$name]))
     {
          return true;
     } else
     {
	     X::$XERCMS['INCLUDE'][$name] = true;
          $name = explode('#',$name,2);
          if(count($name) == 2)
          {
               $dir = DIR.'libs/';$name[0] = $name[1];
          } else $dir = XERCMS.'XerCMS/Library/';
          return include_once($dir.$name[0].'.php');
     }
}


function c($name) {
     global $XERCMS;
     X::import($name);
	$name = strtoupper($name);
	$name = strpos($name,'#') === false ? $name : strtr($name,array('#'=>''));
	if(isset($XERCMS['INSTANCE'][$name]) && is_object($XERCMS['INSTANCE'][$name])) {
	 	return $XERCMS['INSTANCE'][$name];
	}
	$XERCMS['INSTANCE'][$name] = new $name();
	return $XERCMS['INSTANCE'][$name];
}

function setdotime($act,$time) {
	$_SESSION['dotime'][$act] = $time;
}

function isadmin($extra = array()) {
     if(!$group) 
          return false;
     $ret = 0;
     if(in_array($group,X::$G['admingroup'])) {
          $ret += 1;   
     }
     if(in_array($group,X::$G['superadmin'])) {
          $ret += 2;          
     }
     return $ret;
}

function match($p,$s) {
	if(empty($p) || empty($s)) {
		return false;
	}
	$p = strtr($p,array('('=>'\\(',')'=>'\\)'));
	return preg_match('/'.$p.'/i',$s);
}

function runsql($sql) {
     $sql = explode(";\r\n",$sql);
	foreach($sql as $val) {
		DB::query($val);
	}
}

function exts($name,$id,$key = 'name') {
	global $caches;
	$id = $id == '()' ? '' : mb_substr($id,1,(strlen($id) - 2));
	if(empty($id)) {
    		return '';
  	} else  $id = explode(')(',$id);
  	$ids = '';
  	foreach($id as $v) {
   		$ids .= extend($name,$v,$key).' ';
  	}
  	return $ids;
}

function extendId($name = 'letter',$val) {
  	global $caches;
  	if(isset($caches['_extend'][$name]) == false) {
    		include(INC.'caches/extend/'.$name.'.php');
		$caches['_extend'][$name] = $extend[$name];
  	}
  	foreach($caches['_extend'][$name] as $k=>$v) {
    		if(isset($v['name']) && $v['name'] == $val) {
	  		return $k;
		}
  	}
  	return '0';
}

function sVar($str,$id = null,$key = 'name') {
     if(!isset(X::$G['CACHES_STRUCT_VAR'][$str]))
	     X::$G['CACHES_STRUCT_VAR'][$str] = X::import(XERCMS.'XerCMS/Data/#sVar/'.$str.'.php',null);	  
	if($id === null)
	     return X::$G['CACHES_STRUCT_VAR'][$str];
     if(empty(X::$G['CACHES_STRUCT_VAR'][$str]))
	     return '';
	if(isset(X::$G['CACHES_STRUCT_VAR'][$str][$id][$key]) && !empty($id))
	     return X::$G['CACHES_STRUCT_VAR'][$str][$id][$key];
	$ret = current(X::$G['CACHES_STRUCT_VAR'][$str]);
	return $ret[$key];
}

function extend($name,$id,$key = 'name') {
  	global $caches;
  	if(isset($caches['_extend'][$name])) {
    		return isset($caches['_extend'][$name][$id][$key]) ? $caches['_extend'][$name][$id][$key] : '';
  	} else {
    		include_once(INC.'Caches/extend/'.$name.'.php');
		$caches['_extend'][$name] = $extend[$name];
    		return isset($extend[$name][$id][$key]) ? $extend[$name][$id][$key] : '';
  	}
}

function editor($name,$content = '',$width = 0,$height = 0,$option = '') {
  	c('editor')->push($name,$content,$width,$height,$option);
}

function strfilter($str) {
  	return strtr($str,array('\''=>'','"'=>'','<'=>'','>'=>'',' '=>'','\\'=>'','#'=>'','/*'=>''));
}

function strsafe($var) {
  	$filter = array('\'','"','<','>','\\');
	foreach($filter as $v) {
		if(is_array($var)) {
			foreach($var as $str) {
				if(strpos($str,$v) !== false) {
					return false;
	    			}    
	  		}
		} else {
      		if(strpos($str,$v) !== false) {
	    			return false;
	  		}
		}
  	}
  	return true;
}

function htmlstr($var) {
  	if(is_string($var)) {
		return strtr($var,array('\''=>'&#039;','"'=>'&amp;','<'=>'&lt;','>'=>'&gt;',' '=>'&nbsp;','\\'=>''));
	} else return '';
}

function urlback($tip = '') {
	if(isset($_SERVER['HTTP_REFERER'])) {
    		$url = explode('/',$_SERVER['HTTP_REFERER'],4);
         	if(count($url) == 4) {
			showtips($tip,'http://'.X::$G['domain'].'/'.$url[4]);
		}
	}
	showtips($tip,X::$G['domain']);
}

function safe() {
	if(!get_magic_quotes_gpc()) {
    		$_POST = slashes($_POST);
    		$_GET = slashes($_GET);
    		$_COOKIE = slashes($_COOKIE);
    		$_REQUEST = slashes($_REQUEST);
  	}
}

function version() {
  	list($usec, $sec) = explode(' ', X::$G['runtime']);
  	X::$G['runtime'] = ((float)$usec + (float)$sec);
  	list($usec, $sec) = explode(' ', microtime());
  	$endtime = ((float)$usec + (float)$sec);	
  	return 'Memory:'.ceil(memory_get_usage()/1000).'(KB);Time:'.round(($endtime - X::$G['runtime']),3).'(S);Powered By <a href="http://www.xercms.com" target="_blank">XerCMS '.X::$G['version'].'</a>';
}

function slashes($var,$strip = false) {
  	if(is_array($var)) {
    		foreach($var as $k=>$v) {
			$var[$k] = slashes($v,$strip);
		}
	} else $var = $strip ? stripslashes($var) : addslashes($var);
	return $var;
}

function buffer($data,$mode = '') {
     if(X::$CONFIG['gzip']) {
	    return gzip($data);
     }
}

function gzip($html) {
	if(!headers_sent() &&  extension_loaded('zlib') &&  strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')) {
		$html = gzencode($html,9);
		header('Content-Encoding: gzip');  
		header('Vary: Accept-Encoding'); 
	}  
	return $html;  
}

function column($id) {
	global $column,$user;
	if(!empty($column['credits'][1])) {
		credits($column['credits'][0],$column['credits'][1]);
	}
	if(!empty($column['power'])) {
		in_array($user['level'],$column['power']) === false && jmp('power.check',$website['home']);
  	}
}

function getads($id) {
  	global $caches,$G;
  	if(isset($caches['_ads'][$id])) {
    		if(X::$G['time'] > $caches['_ads'][$id]['stime'] && $caches['_ads'][$id]['etime'] > X::$G['time']) {
	  		return $caches['_ads'][$id]['content'];
		}
  	}
  	return '';
}

function lang($key,$dir = 'system',$extra = array()) {
     if(strpos($key,'#') === 0) {
          $key = substr($key,1);
          $file = DIR.'Language/'.$dir.'/'.X::$CONFIG['language'].'.php';
     } else $file = INC.'Language/'.$dir.'/'.X::$CONFIG['language'].'.php';
	if(isset(X::$XERCMS[$file])  === false) {
	     X::$XERCMS[$file] = include($file);
	}
	return isset(X::$XERCMS[$file][$key]) ? X::$XERCMS[$file][$key] : $key;
}

function ajaxtips($content,$gourl = '') {
	$content = lang($content);
	include_once(tpl('common/ajaxtips.htm'));
	exit;
}

function showtips($content,$gourl = '',$title = '',$time = 5,$template = 'common/tips.htm') {
  	if(!isset($gourl{0})) {
      	$gourl = dreferer();
  	}
  	$title = empty($title) ? lang(107) : $title;
  	$content = lang($content);
     if(X::$G['format'] == 'json') {
          if(isset($gourl{0})) {
               exit(json_encode(array('XerCMS'=>$content,'GoUrl'=>$gourl)));
          } else exit(json_encode(array('XerCMS'=>$content)));         
     }
  	include_once(tpl($template));
  	exit;
}


function format($time,$out = 'Y-m-d') {
  	if(empty($time)) {
    		return '';
  	}
  	return date($out,(int)$time);
}

function cutstr($str,$len,$start = 0) {
  	return mb_substr($str,$start,$len);
}

function t($name) {
  	$name = explode('#',$name);
  	if(isset($name[1])) {
		return tpl('/XerCMS/Modules/'.X::$G['module'].'/template/'.$name[1]);
  	} else return tpl($name[0]);
}

function i($str) {
    	list($t,$n) = explode('.',$str,2);
    	if ($t == 'm') {
          $class = 'XerCMS_Interface_'.$n;
          if(isset($XERCMS[$class])) return $XERCMS[$class];
	     include(INC.'Modules/'.$n.'/libs/'.$class.'.php');
	     $XERCMS[$class] = new $class();
	     return $XERCMS[$class];
    	} 
}

function tpl($path) {
	if(strpos($path,':') !== false) {
      	list($id,$name) = explode(':',$path,2);
          $cacheId = md5('XerCMS/Plugins/'.$id.'/template/'.$name);
          if(file_exists(INC.'Caches/template/'.$cacheId.'.php')) {
               hooks(3);
               return INC.'Caches/template/'.$cacheId.'.php';
          }
          if(X::$compiler == NULL) {
               X::import('compiler');
			X::$compiler = new compiler();
          }
	  	X::$compiler->Set('XerCMS/Plugins/'.$id.'/template/',$name,$cacheId);
	  	X::$compiler->parse();
	  	$tpl = X::$compiler->file();
	} else if(strpos($path,'#') !== false) {
		list($name,$file) = explode(':',$path,2);
          $cacheId = md5('XerCMS/Modules/'.$name.'/template/'.$name);
          if(file_exists(INC.'Caches/template/'.$cacheId.'.php')) {
               hooks(3);
               return INC.'Caches/template/'.$cacheId.'.php';
          }    
          if(X::$compiler == NULL) {
               X::import('compiler');
			X::$compiler = new compiler();
          }  
	     X::$compiler->Set('XerCMS/Modules/'.$name.'/template/',$file,$cacheId);
	     X::$compiler->parse();
	     $tpl = X::$compiler->file();
	} else {
	  	$cacheId = md5('Template/'.X::$CONFIG['tplname'].'/'.(MOBILE ? X::$CONFIG['tpldir2'] : X::$CONFIG['tpldir']).'/'.$path);
          if(file_exists(INC.'Caches/template/'.$cacheId.'.php')) {
               hooks(3);
               return INC.'Caches/template/'.$cacheId.'.php';
          }  
          if(X::$compiler == NULL) {
               X::import('compiler');
			X::$compiler = new compiler();
          }
          X::$compiler->Set('Template/'.X::$CONFIG['tplname'].'/'.(MOBILE ? X::$CONFIG['tpldir2'] : X::$CONFIG['tpldir']).'/',$path,$cacheId);
	  	X::$compiler->parse();
	  	$tpl = X::$compiler->file();
	}
	hooks(3);
	return $tpl;
}

function readtext($file) {
	if(is_file(XERCMS.$file)) {
		return file_get_contents(XERCMS.$file);
  	} else false;
}

function putfile($file,$put,$mode = 'w+') {
  	$handle = fopen(XERCMS.$file,$mode);
  	if($handle == false) {
		if(chmod(dirname(XERCMS.$file),0777)) {
			$handle = fopen(XERCMS.$file,$mode);
		} else SysError(106,'/'.dirname($file));
  	}  //SysError(106);
  	fwrite($handle,$put);
  	fclose($handle);
}

function page() {
     return int1(g('page'));
}

function input($key,$method = 0) {
	switch($method) {
		case 1 : //GET
			return G($key);
		break;
    		case 2 : //POST
	  		return G($key);
		break;
		default:
	  		return isset($_GET[$key]) ? $_GET[$key] : (isset($_POST[$key]) ? $_POST[$key] : '');
		break;
  	}
}

function g($key,$default = '') {
  	return isset($_GET[$key]) ? $_GET[$key] : $default;
}

function p($key,$default = '') {
  	return isset($_POST[$key]) ? $_POST[$key] : $default;
}

function member() {
  	if(isset($_SESSION['uid']) && $_SESSION['uid'] > 0) {
		X::$G = array_merge(X::$G,$_SESSION);
  	} else {
    		X::$G['uid'] = 0;
    		X::$G['nick'] = '';
    		X::$G['group'] = 0;  
  	}
}

function todate($time,$format) {
  	return date($format,$time);
}

function urlParam($key,&$data,$mode = 1) {
     if(isset($data[$key])) {
          return $mode == 1 ? '&'.$key.'='.$data[$key] : $data[$key];
     } else return $mode == 1 ? '' : '0';
}

function url($key) {
     if(empty(X::$CONFIG['#links'])) {
          X::$CONFIG['#links'] = ini('links/'.X::$CONFIG['urlmode']);
     }
     if(isset(X::$CONFIG['#links'][$key])) {
          return X::$CONFIG['#links'][$key];
     } else return x::$G['urlpath'];
}

function embed($data) {
     pLoadCall($data);
}

function pLoadCall($data) {
     if(isset(X::$XERCMS['INSTANCE'][$data['class']]) == false && file_exists(INC.$data['file'])) {	
          $pid = explode('/',$data['file']);
		if(isset(X::$XERCMS['PLUGIN'][$pid[1]]['CONFIG']) == false) {
		     X::$XERCMS['PLUGIN'][$pid[1]]['CONFIG'] = ini('plugin/'.$pid[1]);
          }
          isset(X::$XERCMS['INCLUDE'][$data['file']]) == false && include(INC.$data['file']);
		if(class_exists($data['class'],false)) {
		     X::$XERCMS['INSTANCE'][$data['class']] = new $data['class']();
		}         
     }
     if(isset(X::$XERCMS['INSTANCE'][$data['class']]) && is_object(X::$XERCMS['INSTANCE'][$data['class']]) && method_exists(X::$XERCMS['INSTANCE'][$data['class']],$data['method'])) {
          X::$XERCMS['INSTANCE'][$data['class']]->$data['method']();
     }
     X::$XERCMS['INCLUDE'][$data['file']] = true;
}

function hook($data) {
  	pLoadCall($data);
}

function hooks($order,$type = 0) {
  	if(isset(X::$CONFIG['hook_'.$order])) {
		foreach(X::$CONFIG['hook_'.$order] as $val) {
			if(!empty($val['file']) && ($val['type'] == 0 || $type == $val['type'])) {
                    if(empty($val['module']) || ($val['module'] == X::$G['module'] && 
                              (empty($val['enter']) || ($val['enter'] == X::$G['enter'] &&
                                   (empty($val['action']) || $val['action'] == X::$G['action']))))) {
                              hook($val);
                    }
               }				
	  	}
	}
}

function close() {
     if(isset($_GET['format']) && ($_GET['format'] == 'xml' || $_GET['format'] == 'json')) {
		error(112,X::$G['close']);
	} else showtips(X::$G['close']);
}

function sortSqlData($name,$SqlStr,$NoSortSql) {
     $ret = array();
	if(empty($name) || empty($SqlStr)) {
		return DB::fetch_all($NoSortSql);
	}
	if(strpos($name,'.')) {
	   	$tab = explode('.',$name);
	   	$name = strtr($tab[1],array('`'=>''));
	   	$tab = $tab[0].'.';  
	} else $tab = '';
	$data = DB::fetch_all($SqlStr);
     foreach($data as $k=>$v) {
	     $ret[] = $v[$name];
	}
	if(empty($data)) {
	     return array();
	} 
	$sqltail = explode('ORDER BY',$SqlStr,2);$sqltail = count($sqltail) == 2 ? ' ORDER BY '.$sqltail[1] : ''; 
	return DB::fetch_all($NoSortSql.' AND '.$tab.'`'.$name.'` IN ('.implode(',',$ret).')'.$sqltail);
}

function cache($index,$sql = '',$time = 3600,$path = 'data') {
     if($path == 'data') {
       	cachedata($index,$sql,$time);
	} else if ($path == 'frag') {
	     $update = false;
		if(is_file(INC.'caches/'.$path.'/'.$index.'.php')) {
		     X::$CACHES['sql_'.$index] = include(INC.'caches/frag/'.$index.'.php');
			if(X::$CACHES['sql_'.$index]['expired'] < X::$G['time']) {
    	            	$update = true;
			}
		} else $update = true;
		if($update) {
    	       	X::$CACHES['sql_'.$index]['data'] = is_array($sql) ? $sql : c('mysql')->data($sql);
    	       	X::$CACHES['sql_'.$index]['data'] = empty(X::$CACHES['sql_'.$index]['data']) ? array() : X::$CACHES['sql_'.$index]['data'];
	 	     X::$CACHES['sql_'.$index]['expired'] = X::$G['time'] + $time; 
               dfile('XerCMS/Caches/'.$path.'/'.$index.'.php','<?php !defined(\'XERCMS\') && exit(\'Access Denied\'); return '.AtoS(X::$CACHES['sql_'.$index]).'; ?>');
		}
	}
}

function cachedata($index,$sql = '',$time = 3600) {
  	if(isset(X::$CACHES[$index]['sql'])) {
    		X::$CACHES[$index]['data'] =  sortSqlData(X::$CACHES[$index]['sortId'],X::$CACHES[$index]['sortSql'],X::$CACHES[$index]['sql']);
    		X::$CACHES[$index]['data'] = empty(X::$CACHES[$index]['data']) ? array() : X::$CACHES[$index]['data'];
    		X::$CACHES[$index]['expired'] = X::$G['time'] + $time;    
  	} else {
    		X::$CACHES[$index]['data'] = DB::fetch_all($sql);
    		X::$CACHES[$index]['data'] = empty(X::$CACHES[$index]['data']) ? array() : X::$CACHES[$index]['data'];
    		X::$CACHES[$index]['expired'] = X::$G['time'] + $time;
  	}
  	dfile('/XerCMS/Caches/data/'.CACHE.'.php','<?php /*Autor: Arno[QQ:1328013];*/ !defined(\'XERCMS\') && exit(\'Access Denied\');$caches = '.AtoS(X::$CACHES[$index]).'; ?>');
  	return;
}

function db() {
  	return c('mysql');
}
?>